using Microsoft.Extensions.Options;
using Scheduling.Api.Read.Models;
using Scheduling.Api.Read.Options;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

namespace Scheduling.Api.Read.Services
{
    public class XunfeiService : IXunfeiService
    {
        private readonly HttpClient _httpClient;
        private readonly XunfeiOptions _options;
        private readonly ILogger<XunfeiService> _logger;

        public XunfeiService(HttpClient httpClient, IOptions<XunfeiOptions> options, ILogger<XunfeiService> logger)
        {
            _httpClient = httpClient;
            _options = options.Value;
            _logger = logger;
        }

        public async Task<string> SendMessageAsync(string message)
        {
            try
            {
                var request = new XunfeiHttpRequest
                {
                    model = _options.HttpApi.Model,
                    messages = new List<Message>
                    {
                        new Message { role = "user", content = message }
                    }
                };

                var json = JsonSerializer.Serialize(request, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });

                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _options.HttpApi.BearerToken);

                var response = await _httpClient.PostAsync(_options.HttpApi.HttpApiUrl, content);
                response.EnsureSuccessStatusCode();

                var responseContent = await response.Content.ReadAsStringAsync();
                var xunfeiResponse = JsonSerializer.Deserialize<XunfeiHttpResponse>(responseContent, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });

                return xunfeiResponse?.choices?.FirstOrDefault()?.message?.content ?? "抱歉，无法获取AI回复。";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送讯飞AI HTTP请求失败");
                return "抱歉，AI服务暂时不可用，请稍后重试。";
            }
        }

        public async Task<string> SendMessageWebSocketAsync(string message)
        {
            // WebSocket实现需要更复杂的逻辑，这里先返回HTTP API的结果
            // 实际项目中可以集成WebSocket客户端库
            _logger.LogInformation("WebSocket功能暂未实现，使用HTTP API");
            return await SendMessageAsync(message);
        }

        public async Task<string> GetWebSocketUrlAsync()
        {
            try
            {
                // 生成WebSocket连接URL
                var host = "spark-api.xf-yun.com";
                var path = "/v3.1/chat";
                var date = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'");
                var algorithm = "hmac-sha256";
                var headers = "host date request-line";
                var signatureOrigin = $"host: {host}\ndate: {date}\nGET {path} HTTP/1.1";
                var signatureSha = HmacSha256(signatureOrigin, _options.WebSocket.ApiSecret);
                var authorization = $"api_key=\"{_options.WebSocket.ApiKey}\", algorithm=\"{algorithm}\", headers=\"{headers}\", signature=\"{signatureSha}\"";

                var url = $"wss://{host}{path}?authorization={Uri.EscapeDataString(authorization)}&date={Uri.EscapeDataString(date)}&host={host}";
                
                return await Task.FromResult(url);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成WebSocket URL失败");
                return string.Empty;
            }
        }

        private string HmacSha256(string data, string key)
        {
            var keyBytes = Convert.FromBase64String(key);
            var dataBytes = Encoding.UTF8.GetBytes(data);
            
            using var hmac = new HMACSHA256(keyBytes);
            var hashBytes = hmac.ComputeHash(dataBytes);
            return Convert.ToBase64String(hashBytes);
        }
    }
}
